package middleware

import (
	"encoding/json"
	"time"

	"cashway.com/cis/assistant/config"
	"cashway.com/cis/assistant/types"
	"github.com/sirupsen/logrus"
)

func UseLogger[T any](handle types.HandleFunc[T]) types.HandleFunc[T] {
	return func(resp *types.ResponseWriter, req *types.Request[T]) {
		var start = time.Now()
		channel := make(chan bool)
		if config.Config.EnableParamsLog {
			go func() {
				logrus.Infof("request start: %s %s", req.URL.Path, req.Method)
				jsonReqBodyStr, _ := json.Marshal(req.ReqBody)
				logrus.Infof("req body: %s", jsonReqBodyStr)
				channel <- true
			}()
		}
		handle(resp, req)
		if config.Config.EnableJsonRespBodyLog {
			go func() {
				<-channel
				jsonRespBodyStr, _ := json.Marshal(resp.RespBody)
				logrus.Infof("resp body: %s", jsonRespBodyStr)
				logrus.Infof("request end: %s %s %s", req.URL.Path, req.Method, time.Since(start))
			}()
		}
	}
}
